package com.weatherstation.service;

import com.weatherstation.entity.User;
import com.weatherstation.mapper.UserMapper;
import com.weatherstation.security.JwtTokenUtil;
import com.weatherstation.security.RedisTokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AuthService {

    private final AuthenticationManager authenticationManager;
    private final UserDetailsService userDetailsService;
    private final JwtTokenUtil jwtTokenUtil;
    private final RedisTokenManager redisTokenManager;
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public AuthService(AuthenticationManager authenticationManager,
                      UserDetailsService userDetailsService,
                      JwtTokenUtil jwtTokenUtil,
                      RedisTokenManager redisTokenManager,
                      UserMapper userMapper,
                      PasswordEncoder passwordEncoder) {
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
        this.jwtTokenUtil = jwtTokenUtil;
        this.redisTokenManager = redisTokenManager;
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return 包含令牌和用户信息的Map
     * @throws Exception 如果认证失败
     */
    public Map<String, Object> login(String username, String password) throws Exception {
        try {
            // 验证用户名和密码
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password)
            );
            
            // 检查用户角色是否为禁用用户
            User user = userMapper.findByUsername(username);
            if (user != null && "baned_user".equals(user.getRoleCode())) {
                throw new DisabledException("用户已被禁用");
            }
            
            // 生成JWT令牌
            final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            final String token = jwtTokenUtil.generateToken(userDetails);
            
            // 保存令牌到Redis
            redisTokenManager.saveToken(username, token);
            
            // 返回令牌和用户信息
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("username", username);
            
            result.put("roleCode", user.getRoleCode());
            
            return result;
        } catch (DisabledException e) {
            throw new Exception("用户已被禁用", e);
        } catch (BadCredentialsException e) {
            throw new Exception("用户名或密码错误", e);
        }
    }

    /**
     * 用户注销
     * @param username 用户名
     */
    public void logout(String username) {
        redisTokenManager.removeToken(username);
    }

    /**
     * 用户注册
     * @param username 用户名
     * @param password 密码
     * @return 注册成功的用户
     * @throws Exception 如果注册失败
     */
    public User register(String username, String password) throws Exception {
        if (userMapper.existsByUsername(username) > 0) {
            throw new Exception("用户名已存在");
        }
        
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setRoleCode("normal_user");  // 默认为普通用户
        user.setIsDeleted(false);
        
        userMapper.insert(user);
        return user;
    }
} 